<template>
  <div>
    <template v-if="!isInPCDingTalk">
      <div v-if="!isAutoLoginTag" class="login-container">
        <el-dialog :visible.sync="isShowTips" :append-to-body="true" :before-close="handleClose" class="small-common-dialog-size login-tips">
          <div class="tips-title">温馨提示</div>
          <img :src="login_tip" style="width: 200px;" alt="repairing..." >
          <div class="tips-text">服务器维护中</div>
          <div>请您耐心等待维护完成通知或稍后尝试<span class="refresh-btn" @click="refreshPage"><i class="el-icon-refresh" /><span style="text-decoration: underline;">刷新</span></span>页面</div>
        </el-dialog>
        <div v-show="!showMobilePage" class="login-box">
          <div class="login-img">
            <div class="login-img-main">
              <div class="login-main-box">
                <div class="login-title-box">
                  <img :src="configData.logo.img || CRMLogo" :style="configData.logo.style" alt="logo" >
                  <div :style="configData.title.style" class="login-text">{{ configData.title.text || '' }}</div>
                </div>
                <div :style="configData.keyword.style" class="login-desc">{{ configData.keyword.text || '' }}</div>
                <div :style="configData.description.style" class="login-desc-light">{{ configData.description.text || '' }}</div>
              </div>
              <img :src="illustration" class="illustration" alt="">
            </div>
          </div>
          <div class="login-main">
            <transition :appear="true" name="fade">
              <div class="login-content">
                <loginFrom v-show="loginType === 'form'" @tapLoginTap="tapLoginTap" @loginError="loginError" />
                <DingTalkLogin v-show="loginType === 'dingding'" :show-title="isAllowFormLogin" :is-in-ding-talk="isInDingTalk" @tapLoginTap="tapLoginTap" @onTapAuto="autoLogin"/>
              </div>
            </transition>
          </div>
        </div>
        <div v-show="showMobilePage" :class="{ 'login-box-scroll': !isMobile }" class="login-box-mobile">
          <div class="login-background">
            <img :src="login_bg_mobile" alt="bg" >
          </div>
          <div class="login-main">
            <div class="login-content">
              <div class="login-title-box-mobile">
                <div class="login-row">
                  <img :src="logo_mobile" :style="configData.logo.style" alt="logo" >
                  <div :style="configData.title.style" class="login-text">{{ configData.title.text || '' }}</div>
                </div>
                <div class="login-row">
                  <div :style="configData.keyword.style" class="login-desc">{{ configData.keyword.text || '' }}</div>
                  <div :style="configData.description.style" class="login-desc">{{ configData.description.text || '' }}</div>
                </div>
              </div>
              <loginFrom v-show="loginType === 'form'" @tapLoginTap="tapLoginTap" @loginError="loginError" />
              <DingTalkLogin v-show="loginType === 'dingding'" :feishu-qrcode-id="'feishu_qrcode_id'" :dd-qrcode-id="'dd_qrcode_id'" :show-mobile-page="showMobilePage" :show-title="isAllowFormLogin" :is-in-ding-talk="isInDingTalk" @tapLoginTap="tapLoginTap" @onTapAuto="autoLogin"/>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <div v-if="!isAutoLoginTag" class="login-auto-container">
        <div class="pc-ding-talk-login-main">
          <div class="logo">
            <img :src="CRMLogo" class="logo-img" alt="logo">
          </div>
          <div class="text">已在外部浏览器打开</div>
          <div style="display:flex;justify-content:center;margin-top: 20px;">
            <el-button size="mini" type="primary" @click="fresh">重新打开</el-button>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import DingTalkLogin from './ddlogin';
// img
import CRMLogo from '@/assets/crm-logo.png';
import login_tip from '@/assets/login-tip.png';
import login_bg_mobile from '@/assets/login-bg-mobile.png';
import logo_mobile from '@/assets/logo-mobile.png';
import illustration from '@/assets/illustration.png';
// component
import loginFrom from './loginForm';
import ddLogin from '@/mixins/ddLogin';
import { openNewWindow } from '@/utils/index';
const HAS_AUTO_TAG = 'HAS-AUTO-LOGIN';
import { getLoginPageConfig } from '@/api/login';
import { setMetaViewport } from '@/utils/tools';

export default {
  name: 'Login',
  components: {
    DingTalkLogin, loginFrom
  },
  mixins: [ddLogin],
  data() {
    return {
      CRMLogo, login_tip, login_bg_mobile, logo_mobile,
      illustration,
      loginType: 'form',
      isAutoLoginTag: true,
      isAllowFormLogin: false,
      urltt: '',
      isShowTips: false,
      networkStatus: true,
      configData: {
        logo: {
          img: CRMLogo,
          style: ''
        },
        title: {
          text: '共创平台',
          style: ''
        },
        keyword: {
          text: '智能·协同·高效',
          style: ''
        },
        description: {
          text: '让流程更快捷',
          style: ''
        }
      },
      showMobilePage: false,
      container: null,
      resizeObserver: null
    };
  },
  computed: {
    ...mapState({
      'token': state => state.token
    })
  },
  watch: {
    'showMobilePage': {
      handler(val) {
        if (val) setMetaViewport('1.0', '1.0', '1.0');
        const idObj = {
          feishuId: 'feishu_qrcode_id',
          ddId: 'dd_qrcode_id'
        };
        this.onChangeLoginType(val ? idObj : null);
      }
    }
  },
  created() {
    this.getLoginPageConfig();
    this.isAllowFormLogin = this.$route.query.allowFormLogin === '1' || process.env.NODE_ENV === 'alpha' || process.env.NODE_ENV === 'development'; // 开启账号登录
    if (this.$route.query.allowFormLogin) {
      sessionStorage.removeItem('isShowTips');
    }
    if (!this.isAllowFormLogin) this.loginType = 'dingding';
    this.isAutoLoginTag = this.isInDingTalk && this.isAutoLogin();
    this.urltt = location.href;
  },
  mounted() {
    window.addEventListener('online', () => {
      this.networkStatus = true;
    });
    window.addEventListener('offline', () => {
      this.networkStatus = false;
    });
    const query = new URLSearchParams(location.search || '?');
    const isFeishuAutoLogin = query.get('isFeishu') || this.isInFeishu; // 重定向
    console.log(query.get('redirect'));
    if (this.isInDingTalk) {
      this.loginType = 'dingding';
      if (this.isAutoLogin()) {
        this.$message('正在授权登录中...');
        this.autoLogin();
        this.closeAutoLogin();
      }
    } else if (isFeishuAutoLogin) {
      this.feishuAutoLogin();
    } else {
      const idObj = {
        feishuId: 'feishu_qrcode_id',
        ddId: 'dd_qrcode_id'
      };
      this.onChangeLoginType(this.isMobile ? idObj : '');
    }
    this.handleIsShowTips();
    // this.feishuAutoLogin();
    if (!this.isMobile) {
      this.handleWindowSizeChange();
    } else {
      this.showMobilePage = this.isMobile;
    }
  },
  beforeDestroy() {
    if (this.resizeObserver) this.resizeObserver.unobserve(this.container);
  },
  methods: {
    handleWindowSizeChange() {
      this.container = document.querySelector('.login-container');
      this.resizeObserver = new ResizeObserver(entries => {
        for (const entry of entries) {
          if (entry.contentBoxSize) {
            const contentBoxSize = Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0] : entry.contentBoxSize;
            // 窗口尺寸小于375或宽高比小于0.75时展示成移动端页面
            this.showMobilePage = contentBoxSize.inlineSize < 375 || (contentBoxSize.inlineSize / contentBoxSize.blockSize < 0.75);
            this.isInitFeishuCode = false;
            this.isInitCode = false;
          }
        }
      });
      this.resizeObserver.observe(this.container);
    },
    handleIsShowTips() {
      // 飞书、钉钉登录报错弹窗提示
      const isShowTips = sessionStorage.getItem('isShowTips');
      if (isShowTips && this.networkStatus) {
        this.isShowTips = true;
      }
    },
    onChangeLoginType(obj) {
      if (this.changeDDCode) { // 判断是否存在fun
        this.changeDDCode(obj);
      }
      this.changeFeishuErCode(obj);
    },
    tapLoginTap() {
      const isFormType = this.loginType === 'form';
      if (!isFormType && !this.isAllowFormLogin) {
        this.$message.error('账密登录已禁用，请联系管理员！');
      } else {
        this.loginType = isFormType ? 'dingding' : 'form';
      }
    },
    refreshPage() {
      sessionStorage.removeItem('isShowTips');
      location.reload();
    },
    handleClose() {
      this.isShowTips = false;
    },
    loginError() {
      this.isShowTips = true;
    },
    isAutoLogin() {
      return !sessionStorage.getItem(HAS_AUTO_TAG) && !this.token && !localStorage.getItem('loginCode');
    },
    closeAutoLogin() {
      sessionStorage.setItem(HAS_AUTO_TAG, 1);
    },
    fresh() {
      const query = new URLSearchParams(location.search || '?');
      let redirect = query.get('redirect');
      let path = '';
      if (redirect && redirect !== 'null') {
        for (const [key, value] of query.entries()) {
          if (key !== 'redirect' && value) {
            redirect += `${redirect.indexOf('?') < 0 ? '?' : '&'}${key}=${value}`;
          }
        }
        path = '?redirect=' + redirect;
        console.log('login:', path);
      }
      openNewWindow(location.origin + path);
    },
    getLoginPageConfig() {
      getLoginPageConfig().then(res => {
        if (res.data) {
          this.configData = JSON.parse(res.data);
        }
      }).catch(err => console.error(err));
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login-tips {
  &::v-deep {
    .el-dialog__body {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-flow: column nowrap;
      .tips-title {
        font-size: 24px;
        font-family: PingFang SC, PingFang SC-Medium;
        font-weight: 500;
        color: #333333;
        line-height: 20px;
        margin-bottom: 44px;
      }
      .tips-text {
        margin: 19px 0 8px;
        font-size: 16px;
        font-family: PingFang SC, PingFang SC-Medium;
        font-weight: 500;
        color: #333333;
        line-height: 16px;
      }
      .refresh-btn {
        color: #406EFF;
        margin: 0 2px;
        cursor: pointer;
      }
    }
  }
}
.login-container {
  .login-box {
    @include scrollBar($x: auto, $y: auto, $width: 10px);
    display: flex;
    height: 100vh;
    .login-main {
      width: 61%;
      height: 100%;
      min-width: 565px;
      position: relative;
    }
    .login-img {
      flex: 1;
      position: relative;
      overflow: hidden;
      min-width: 455px;
      background: url('~@/assets/login-bg.png') no-repeat;
      height: 100%;
      .login-main-box {
        padding-left: 88px;
        z-index: 1;
        .login-title-box {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          margin: 96px 0 40px;
          position: relative;
          z-index: 3;
          img {
            width: 39px;
          }
          .login-text {
            margin-left: 16px;
            font-size: 32px;
            font-family: PingFangSC-Semibold;
            text-align: left;
            color: #000000;
            line-height: 62px;
            letter-spacing: 7.76px;
            white-space: nowrap;
          }
        }
        .login-desc {
          font-size: 44px;
          font-family: PingFangSC-Light;
          color: #333333;
          position: relative;
          z-index: 2;
        }
        .login-desc-light {
          opacity: 0.5;
          font-size: 32px;
          font-family: PingFangSC-Light;
          text-align: left;
          color: #333333;
          margin-top: 24px;
          position: relative;
          z-index: 2;
        }
      }
      .login-img-main {
        height: 100%;
        img {
          width: 100%;
        }
        .illustration {
          position: absolute;
          bottom: 0;
          z-index: 1;
        }
        .text {
          font-size: 16px;
          font-family:PingFangSC-Light,PingFang SC;
          font-weight:300;
          color:rgba(255,255,255,0.9);
          margin-bottom: 20px;
          display: flex;
          align-items: center;
          white-space: nowrap;
          .active {
            margin-left: 10px;
            position: relative;
            z-index: 4;
            width: 50px;
            display: inline-block;
            height: 22px;
            .name {
              position: absolute;
              font-family:PingFangSC-Medium,PingFang SC;
              font-weight:500;
              color:rgba(255,255,255,1);
              width: 100%;
              z-index: 3;
              top: 2px;
            }
            .bottom {
              content: '';
              position: absolute;
              left: 0;
              bottom: 1px;
              height:4px;
              width: 100%;
              z-index: 2;
              background-color: #31CC9C;
            }
          }
        }
      }
    }
  }
  .login-box-mobile {
    height: 100vh;
    overflow: auto;
    &.login-box-scroll {
      @include scrollBar($x: hidden, $y: auto, $width: 6px);
    }
    .login-background {
      height: 40%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .login-main {
      height: calc(60% + 100px);
      padding: 0 64px;
      border-radius: 32px 32px 0 0;
      position: relative;
      bottom: 100px;
      z-index: 2;
      background-color: #fff;
      &::v-deep {
        .login-content {
          width: 100%;
          height: 100%;
          transform: unset;
          max-width: 100%;
          top: 0;
          left: 0;
          position: relative;
          .login-title-box-mobile {
            border-bottom: 1px solid #DDDDDD;
            padding-top: 24px;
            .login-row {
              display: flex;
              align-items: center;
              img {
                width: 64px;
                margin-right: 16px;
              }
              .login-text {
                font-size: 40px;
                font-family: PingFangSC-Semibold;
                color: #000000;
                line-height: 62px;
                letter-spacing: 1.92px;
                white-space: nowrap;
              }
              .login-desc {
                font-size: 16px;
                font-family: PingFang SC, PingFang SC-Light;
                font-weight: 300;
                color: #aeb6c7;
                letter-spacing: 0.77px;
                &:first-child {
                  margin-right: 8px;
                }
              }
            }
          }
          .dd-login-container {
            box-shadow: none;
            border-radius: unset;
            height: 100%;
            &>div {
              height: 100%;
              .login-title {
                img {
                  right: -32px;
                }
              }
              .login-tab-center {
                width: 100%;
                .login-tab {
                  width: 100%;
                  margin-top: 12px;
                  .el-tabs__header {
                    .el-tabs__nav-prev, .el-tabs__nav-next {
                      display: none;
                    }
                    .el-tabs__nav-wrap {
                      padding: 0;
                    }
                    .el-tabs__nav-scroll {
                      justify-content: center;
                      .el-tabs__active-bar {
                        // width: 168px !important;
                        height: 3px;
                      }
                    }
                    .el-tabs__item {
                      padding-bottom: 12px;
                    }
                    .tab-title {
                      font-size: 16px;
                      color: #666666;
                    }
                    .is-active {
                      .tab-title {
                        color: #406EFF;
                      }
                    }
                  }
                }
              }
              .tip {
                font-size: 14px;
                font-weight: 400;
                color: #999999;
                line-height: 25px;
                margin: 12px 0 16px;
              }
              .auth-btn {
                width: 100% !important;
              }
            }
          }
          .feishu-code-container {
            width: 260px;
            height: 280px;
            margin-top: 16px !important;
          }
        }
      }
    }
  }
}

.login-content {
  width: 52%;
  position: absolute;
  width: 400px;
  left: 50%;
  // top: 100px;
  top: 50%;
  transform: translate(-50%,-50%);
  .logo {
    width: 100%;
    position: relative;
    .logo-img {
      width: 100%;
      display: block;
      margin: 0 auto;
    }
    .small-logo-img {
      width: 40px;
      margin-bottom: 20px;
    }
  }
}
.login-auto-container {
  overflow: hidden;
}
.pc-ding-talk-login-main {
  width: 400px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  .logo {
    width: 100%;
    position: relative;
    margin: 0 auto;
    .logo-img {
      width: 100%;
      display: block;
      margin: 0 auto;
    }
    .small-logo-img {
      width: 40px;
      margin-bottom: 20px;
    }
  }
  .text {
    font-size: 22px;
    text-align: center;
    margin-top: 40px;
  }
}
.fade-enter-active, .fade-leave-active {
  transition: all .6s ease-in-out;
}
.fade-enter-to, .fade-leave-to {
  transition: all .6s ease-in-out;
}
</style>
<style lang="scss">
.login-tooltip {
  background-color: #406EFF !important;
  box-shadow:3px 5px 15px 0px rgba(188,206,243,1);
  // display: block !important;
  // left: 200px;
  // top: 200px;
  border-radius: 4px !important;
  .popper__arrow {
    display: block !important;
    top: 6px !important;
    border-right-color: #406EFF !important;
  }
  &.el-tooltip__popper[x-placement^=right] .popper__arrow:after {
    border-right-color: #406EFF !important;
  }
}

</style>
